package zhongbo.java.air.monitor.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhongbo.java.air.common.util.AssertUtil;
import zhongbo.java.air.common.vo.PageVo;
import zhongbo.java.air.monitor.dto.AirAlertZoneDto;
import zhongbo.java.air.monitor.mapper.AlertLogMapper;
import zhongbo.java.air.monitor.model.AlertLog;
import zhongbo.java.air.monitor.service.IAlertLogService;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 说明：
 *
 * @author 钟波dellNotebook
 * @since 2025年04月09日 星期三 21:56:09
 */
@Service
@Slf4j
public class AlertLogServiceImpl implements IAlertLogService<AlertLog> {

    @Autowired
    private AlertLogMapper alertLogMapper;

    @Override
    public AlertLog add(AlertLog alertLog) {
        validAlertLog(alertLog);
        AssertUtil.isNull(alertLog.getId(), "实体id不能填写");

        int insert = alertLogMapper.insert(alertLog);
        if (insert > 0) {
            return alertLog;
        }
        throw new RuntimeException("新增实体失败");
    }

    /**
     * 通用验证实体信息
     */
    private void validAlertLog(AlertLog alertLog) {
        if (alertLog == null) {
            throw new RuntimeException("实体信息不能为空");
        }
        AssertUtil.maxLength(alertLog.getIcaoCode(), 6, "ICAO码不能超过6位");
        AssertUtil.notBlank(alertLog.getIcaoCode(), "ICAO码不能为空");
    }

    @Override
    public String delete(String alertLogId) {
        if (StrUtil.isBlank(alertLogId)) {
            throw new RuntimeException("实体id不能为空");
        }
        int delete = alertLogMapper.deleteById(alertLogId);
        if (delete > 0) {
            return alertLogId;
        }
        throw new RuntimeException("删除实体失败");
    }

    @Override
    public AlertLog edit(AlertLog edit) {
        validAlertLog(edit);
        String alertLogId = edit.getId();
        if (StrUtil.isBlank(alertLogId)) {
            throw new RuntimeException("实体id不能为空");
        }
        AlertLog one = findOne(alertLogId);
        if (one == null) {
            throw new RuntimeException("实体不存在");
        }
        int update = alertLogMapper.updateById(edit);
        if (update > 0) {
            return edit;
        }
        throw new RuntimeException("修改实体失败");
    }

    @Override
    public AlertLog findOne(String alertLogId) {
        if (StrUtil.isBlank(alertLogId)) {
            throw new RuntimeException("实体id不能为空");
        }
        return alertLogMapper.selectById(alertLogId);
    }

    @Override
    public PageVo<AlertLog> findPage(Integer page, Integer pageSize
            , String icao, String startDate, String endDate
            , String keyword, String fields, String oderByField, Boolean orderByAsc) {
        QueryWrapper<AlertLog> queryWrapper = new QueryWrapper<>();
        // 检测是否有排序
        if (StrUtil.isNotBlank(oderByField)) {
            // 检测是正序还是倒序
            boolean isOrderByAsc = Boolean.TRUE.equals(orderByAsc);
            if (isOrderByAsc) {
                // 结果正序排列
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(oderByField));
            } else {
                // 否则结果倒序排列
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(oderByField));
            }
        }
        // 支持指定字段模糊搜索keyword
        if (StrUtil.isNotBlank(keyword) && StrUtil.isNotBlank(fields)) {
            String[] fieldsArray = fields.split(",");
            for (String field : fieldsArray) {
                queryWrapper.or().like(StrUtil.toUnderlineCase(field), keyword);
            }
        }
        // 查询icao编码
        if (StrUtil.isNotBlank(icao)) {
            queryWrapper.eq("icao_code", icao);
        }
        // 查询时间范围
        if (StrUtil.isNotBlank(startDate)) {
            queryWrapper.ge("date", startDate);
        }
        if (StrUtil.isNotBlank(endDate)) {
            queryWrapper.le("date", endDate);
        }
        Page<AlertLog> pageParam = new Page<>(page, pageSize);
        Page<AlertLog> alertLogPage = alertLogMapper.selectPage(pageParam, queryWrapper);

        return new PageVo<>(alertLogPage);
    }

    @Override
    public List<AirAlertZoneDto> listAlertZone() {
        return alertLogMapper.listAlertZone();
    }

    @Override
    public Long countMinutesByIcao(String icaoCode, int minutes) {
        if (StrUtil.isBlank(icaoCode)) {
            throw new RuntimeException("icao编码不能为空");
        }
        QueryWrapper<AlertLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("icao_code", icaoCode);
        Date time = new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(minutes));
        String dateTime = DateUtil.formatDateTime(time);
        queryWrapper.ge("trigger_time", dateTime);
        Long selectCount = alertLogMapper.selectCount(queryWrapper);
        log.info("查询icao: {}, 时间大于: {}的告警数量: {} 个", icaoCode, dateTime, selectCount);
        return selectCount;
    }

}
